/**
 * @file 获取数据
 * @author haoxubin
 */
import ERROR from '@/conf/error';
/* eslint-disable */

export default function fetchData(url, data = {}, conf = {}) {
    if (!url) {
        console.error('url不能为空！');
        return;
    }

    const method = (conf.method || 'post').toUpperCase();

    let queryData = '';
    if (conf.type === 'upload') {
        queryData = data;
    } else {
        // eslint-disable-next-line
        if (window.URLSearchParams) {
            queryData = new URLSearchParams(data);
        } else {
            const keys = Object.keys(data);
            for (let i = keys.length - 1; i >= 0; i--) {
                queryData += `&${keys[i]}=${data[keys[i]]}`;
            }
            queryData = queryData.substr(1);
        }
    }
    // console.log(data);
    const timeout = conf.timeout || 5000;
    const interceptors = this && this.$fetch.prototype.interceptors[0];
    let params = {}
    if (method === 'GET') {
        url = url + '?' + queryData;
        params = {
            method,
            mode: 'cors',
            cache: 'force-cache',
            credentials: 'include'
            // body: queryData
        };
    } else {
        params = {
            method,
            body: queryData,
            mode: 'cors',
            cache: 'force-cache',
            credentials: 'include'
        };
    }
    if (window.fetch) {
        // console.log('haha');
        let timer = '';
        const timeoutRes = new Promise((resolve, reject) => {
            timer = setTimeout(() => {
                interceptors && interceptors(ERROR[1101]);
                reject(ERROR[1101]);
            }, timeout);
        });
        const fetchRes = fetch(url, params)
            .then((json) => {
                // console.log(json.status);
                if (json.status === 200) {
                    clearTimeout(timer);
                    return json.json();
                } else {
                    return Promise.reject(ERROR[1014]);
                }
            })
            .then((res) => {
                // console.log(res);
                interceptors && interceptors(res);
                if (res && (res.errorNum === 0 || res.errno === 0) && res.data !== undefined) {
                    return Promise.resolve(res.data);
                }
                if (res.errorNum || res.errno) {
                    interceptors && interceptors(res);
                    return Promise.reject(res);
                }
                return Promise.reject(ERROR[1014]);
            })
            .catch((err) => {
                interceptors && interceptors(err);
                return Promise.reject(err);
            });
        return Promise.race([fetchRes, timeoutRes]);
    }
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open(method, url, true);
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        xhr.withCredentials = true;
        xhr.send(queryData);
        xhr.timeout = timeout;
        xhr.ontimeout = () => reject(ERROR[1101]);
        xhr.onerror = () => reject(ERROR[1014]);
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    let res = xhr.response;
                    if (typeof res !== 'object') {
                        res = JSON.parse(res);
                    }
                    if ((res.errorNum === 0 || res.errno === 0) && res.data !== undefined) {
                        return resolve(res.data);
                    }
                    if (res.errorNum || res.errno) {
                        return reject(res);
                    }
                    return reject(ERROR[1014]);
                }
            }
        };
    });
}

// 0 - (未初始化)还没有调用send()方法
// 1 - (载入)已调用send()方法，正在发送请求
// 2 - (载入完成)send()方法执行完成，
// 3 - (交互)正在解析响应内容
// 4 - (完成)响应内容解析完成，可以在客户端调用了
fetchData.prototype.interceptors = [];
